import 'package:flutter/material.dart';
import '../models/word.dart';
import '../services/database_service.dart';

class DebugScreen extends StatefulWidget {
  const DebugScreen({super.key});

  @override
  State<DebugScreen> createState() => _DebugScreenState();
}

class _DebugScreenState extends State<DebugScreen> {
  final DatabaseService _databaseService = DatabaseService();
  List<String> _logs = [];
  bool _isLoading = false;

  void _addLog(String message) {
    setState(() {
      _logs.add('${DateTime.now().toString().substring(11, 19)}: $message');
    });
    print(message);
  }

  Future<void> _testDatabase() async {
    setState(() {
      _isLoading = true;
      _logs.clear();
    });

    try {
      _addLog('开始测试数据库...');
      
      // 初始化数据库
      _addLog('初始化数据库...');
      await _databaseService.init();
      _addLog('数据库初始化成功');
      
      // 检查现有数据
      _addLog('检查现有数据...');
      final existingWords = await _databaseService.wordRepository.getAllWords();
      _addLog('现有单词数量: ${existingWords.length}');
      
      // 添加测试数据
      _addLog('添加测试单词...');
      final testWord = Word(
        word: 'test',
        translation: '测试',
        example: 'This is a test.',
        category: 'debug',
        difficulty: 1,
      );
      
      final id = await _databaseService.wordRepository.addWord(testWord);
      _addLog('测试单词添加成功，ID: $id');
      
      // 再次检查数据
      _addLog('重新检查数据...');
      final allWords = await _databaseService.wordRepository.getAllWords();
      _addLog('总单词数量: ${allWords.length}');
      
      for (var word in allWords) {
        _addLog('单词: ${word.word} - ${word.translation}');
      }
      
      _addLog('数据库测试完成');
      
    } catch (e) {
      _addLog('测试失败: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _clearDatabase() async {
    try {
      _addLog('清空数据库...');
      await _databaseService.init();
      // 这里需要实现清空功能
      _addLog('数据库清空完成');
    } catch (e) {
      _addLog('清空失败: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('数据库调试'),
        centerTitle: true,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    onPressed: _isLoading ? null : _testDatabase,
                    child: const Text('测试数据库'),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: ElevatedButton(
                    onPressed: _isLoading ? null : _clearDatabase,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.red,
                      foregroundColor: Colors.white,
                    ),
                    child: const Text('清空数据库'),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            if (_isLoading)
              const CircularProgressIndicator()
            else
              Expanded(
                child: Container(
                  width: double.infinity,
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: _logs.map((log) => Padding(
                        padding: const EdgeInsets.only(bottom: 4),
                        child: Text(
                          log,
                          style: const TextStyle(
                            fontFamily: 'monospace',
                            fontSize: 12,
                          ),
                        ),
                      )).toList(),
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}